<script setup lang="ts">
import type { UploadUserFile, UploadProps } from "element-plus"
import type { EntityBaseInfo, SevenCode } from "@@/apis/entity/type"
import type { FormInstance, FormRules } from "element-plus"
import { addTagApi, createEntityDataApi } from "@@/apis/entity/index"
import SelectMilstd from "@@/components/SelectThreeMilstd/index.vue"
import SelectTag from "@@/components/SelectTag/index.vue"
import SelectThree from "@@/components/SelectThreeMilstd/index.vue"
import { nextTick, onMounted, reactive, ref, watch } from "vue"
import { useRouter } from "vue-router"
import { closeRoute } from "@/common/composables/useCloseRouteListener"
import { useFetchSevenCode } from "@@/apis/sevencode/useFetchSevenCode"
import { cloneDeep } from "lodash-es"

defineOptions({
  name: "EntityCreate"
})

const drawer = ref(false)
const router = useRouter()

const {
  kindOptions,
  domainOptions,
  countryOptions,
  categoryOptions,
  subCategoryOptions,
  specificOptions,
  extraOptions,
  sevencode,
  loading: sevenCodeLoading,
  kindChange,
  domainChange,
  countryChange,
  categoryChange,
  subcategoryChange,
  specificChange,
  extraChange
} = useFetchSevenCode()

const DEFAULT_SEVENCODE: SevenCode = {
  kind: -1,
  domain: -1,
  country: -1,
  category: -1,
  subcategory: -1,
  specific: -1,
  extra: -1
}
const DEFAULT_FORM_DATA: EntityBaseInfo = {
  id: undefined,
  code: "",
  name: "",
  tag: [],
  description: "",
  milstdId: "",
  threeId: "",
  entityType: DEFAULT_SEVENCODE
}
const ruleForm = reactive<EntityBaseInfo>(DEFAULT_FORM_DATA)
const insertFiles = ref<UploadUserFile[]>([]) // 附件
function validatePass(rule: any, value: any, callback: any) {
  if (value.length === 0) {
    callback(new Error("请选择标签"))
  } else {
    callback()
  }
}
const rules = ref<FormRules<EntityBaseInfo>>({
  code: [{ required: true, message: "请输入", trigger: "blur" }],
  name: [{ required: true, message: "请输入", trigger: "blur" }],
  tag: [{ validator: validatePass, required: true, trigger: "blur" }],
  description: [{ required: true, message: "请输入", trigger: "blur" }]
})
const ruleFormRef = ref<FormInstance>()
const ruleFormSevenRef = ref<FormInstance>()

// 退出
function exitClick() {
  closeRoute()
  router.back()
}

interface CreateParams extends EntityBaseInfo {
  project_id?: string
}
async function submitForm() {
  const ruleFormValid = !ruleFormRef.value
    ? false
    : await ruleFormRef.value
      .validate()
      .then((valid: boolean) => valid)
      .catch(() => false)

  const ruleFormSevenValid = !ruleFormSevenRef.value
    ? false
    : await ruleFormSevenRef.value
      .validate()
      .then((valid: boolean) => valid)
      .catch(() => false)

  return ruleFormValid && ruleFormSevenValid
}

let fileChangeTimer: ReturnType<typeof setTimeout> | null = null
// function handleBeforeUpd(file: File): boolean {
//   // insertFiles.value = [...insertFiles.value, file]
//   // return false
// }
const handleFileChange: UploadProps["onChange"] = (file: any, fileList: any) => {
  insertFiles.value.push(file)
}
// 提交表单
async function handleSave() {
  const valid = await submitForm()
  if (valid) {
    const fd = new FormData()
    insertFiles.value.forEach((item: any, index: any) => {
      fd.append(`insertFiles[${index}].file`, item.raw)
    })
    const params: CreateParams = {
      id: undefined,
      code: ruleForm.code,
      name: ruleForm.name,
      tag: JSON.stringify(ruleForm.tag),
      description: ruleForm.description,
      milstdId: ruleForm.milstdId,
      threeId: ruleForm.threeId,
      entityType: sevencode.value
    }
    fd.append("businessParam", JSON.stringify(params))
    createEntityDataApi(fd).then(({ data }) => {
      closeRoute()
      router.replace({
        name: "EntityView",
        query: { id: data }
      })
    })
  }
}
watch(() => sevencode.value, (newVal) => {
  ruleForm.entityType = cloneDeep(newVal)
}, { deep: true })
</script>

<template>
  <div class="entity-create-container cc-pane-item">
    <div class="cpi-header">
      <span class="cpi-header-text">基本信息</span>
    </div>
    <div class="entity-create-wrapper">
      <div class="entity-create-table">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-position="top" label-width="auto"
          class="demo-ruleForm">
          <el-row :gutter="24">
            <el-col :sm="24" :md="12" :lg="10">
              <el-form-item label="名称" prop="code">
                <el-input v-model="ruleForm.code" placeholder="请输入" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="10">
              <el-form-item label="别名" prop="name">
                <el-input v-model="ruleForm.name" placeholder="请输入" autocomplete="off" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="10">
              <el-form-item label="标签" prop="tag">
                <SelectTag module="entity" v-model:task_tags="ruleForm.tag" :max-collapse-tags="2" />
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="10">
              <el-form-item label="描述">
                <el-input v-model.number="ruleForm.description" :rows="3" placeholder="请输入" show-word-limit
                  type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="entity-create-table">
        <div class="cpi-content-toolbar">
          <div class="title">
            <span><span style="color: red">*</span>七类码</span>
          </div>
          <el-col :sm="24" :md="12" :lg="8" class="sc-input">
            <el-input-number v-model="sevencode.kind" :controls="false" class="sc-input-number" @change="kindChange" />
            <span>.</span>
            <el-input-number v-model="sevencode.domain" :controls="false" class="sc-input-number"
              @change="domainChange" />
            <span>.</span>
            <el-input-number v-model="sevencode.country" :controls="false" class="sc-input-number"
              @change="countryChange" />
            <span>.</span>
            <el-input-number v-model="sevencode.category" :controls="false" class="sc-input-number"
              @change="categoryChange" />
            <span>.</span>
            <el-input-number v-model="sevencode.subcategory" :controls="false" class="sc-input-number"
              @change="subcategoryChange" />
            <span>.</span>
            <el-input-number v-model="sevencode.specific" :controls="false" class="sc-input-number"
              @change="specificChange" />
            <span>.</span>
            <el-input-number v-model="sevencode.extra" :controls="false" class="sc-input-number"
              @change="extraChange" />
          </el-col>
        </div>
        <el-form ref="ruleFormSevenRef" :model="DEFAULT_SEVENCODE" status-icon :rules="rules"
          :hide-required-asterisk="true" label-position="left" label-width="80px" class="demo-ruleForm">
          <el-row :gutter="24">
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="种类" prop="entityType.kind">
                <el-select v-model="sevencode.kind" popper-class="drawer-select-popper" placeholder="若无选项，默认值为-1"
                  clearable @clear="() => sevencode.kind = -1" @change="kindChange" :loading="sevenCodeLoading.kind">
                  <el-option v-for="item in kindOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="平台" prop="entityType.domain">
                <el-select v-model="sevencode.domain" popper-class="drawer-select-popper" placeholder="若无选项，默认值为-1"
                  clearable @clear="() => sevencode.domain = -1" @change="domainChange"
                  :loading="sevenCodeLoading.domain" :disabled="sevencode.kind === -1">
                  <el-option v-for="item in domainOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="国家/地区" prop="entityType.country">
                <el-select v-model="sevencode.country" popper-class="drawer-select-popper" clearable
                  @clear="() => sevencode.country = -1" @change="countryChange" :loading="sevenCodeLoading.country">
                  <el-option v-for="item in countryOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="类别" prop="entityType.category">
                <el-select v-model="sevencode.category" popper-class="drawer-select-popper" clearable
                  @clear="() => sevencode.category = -1" @change="categoryChange" :loading="sevenCodeLoading.category"
                  :disabled="sevencode.country === -1">
                  <el-option v-for="item in categoryOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="子类" prop="entityType.subcategory">
                <el-select v-model="sevencode.subcategory" popper-class="drawer-select-popper" clearable
                  @clear="() => sevencode.subcategory = -1" @change="subcategoryChange"
                  :loading="sevenCodeLoading.subcategory" :disabled="sevencode.category === -1">
                  <el-option v-for="item in subCategoryOptions" :key="item.value" :label="item.name"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="具体型号" prop="entityType.specific">
                <el-select v-model="sevencode.specific" popper-class="drawer-select-popper" clearable
                  @clear="() => sevencode.specific = -1" @change="specificChange" :loading="sevenCodeLoading.specific"
                  :disabled="sevencode.subcategory === -1">
                  <el-option v-for="item in specificOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :sm="24" :md="12" :lg="8">
              <el-form-item label="拓展型号" prop="entityType.extra">
                <el-select v-model="sevencode.extra" popper-class="drawer-select-popper" clearable
                  @clear="() => sevencode.extra = -1" @change="extraChange" :loading="sevenCodeLoading.extra"
                  :disabled="sevencode.specific === -1">
                  <el-option v-for="item in extraOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="entity-create-upload">
        <div>
          <span class="upload-title">添加军标</span>
          <SelectMilstd v-model:selected-id="ruleForm.milstdId" :entity-name="ruleForm.code" accept=".jpg, .png, .jpeg"
            :id="ruleForm.milstdId" v-model:path="ruleForm.milstdPath" upload-type="milstd" />
        </div>
        <div>
          <span class="upload-title">添加三维模型</span>
          <SelectThree v-model:selected-id="ruleForm.threeId" :entity-name="ruleForm.code"
            accept=".glb, .fbx, .gltf, .obj, .stl, .3ds" :id="ruleForm.threeId" v-model:path="ruleForm.threePath"
            v-model:three-thumb-path="ruleForm.threeThumbPath" upload-type="three-model" />
        </div>
      </div>
      <div class="cpi-header">
        <span class="cpi-header-text">附件</span>
      </div>
      <div>
        <el-upload class="again-upload" :show-file-list="true" action="https://your-api.com/uploadList" ref="upload" :file-list="insertFiles"
          accept=".zip, .pdf, .doc .docx" @change="handleFileChange" :multiple="true">
          <el-button type="success">
            添加附件
          </el-button>
        </el-upload>
      </div>
    </div>
    <div>

    </div>
    <div class="entity-create-submit">
      <el-button @click="exitClick">
        取消
      </el-button>
      <el-button type="primary" @click="handleSave()">
        保存
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

// 在已有样式中添加
.three-container {
  width: 100%;
  height: 250px;
  margin-top: 20px;
  border-radius: 4px;
  overflow: hidden;
}

.img-container {
  width: 100%;
  height: 250px;
  margin-top: 20px;
  border-radius: 4px;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.three-type {
  margin-right: 110px;

  // display: flex;
  // flex-direction: row;
  // justify-content: flex-start;
  // margin-bottom: 10px;
  span {
    display: inline-block;
    background-color: #f5f7fa;
    width: 80px;
    color: #ccc;
    height: 30px;
    margin-right: 10px;
    line-height: 30px;
    text-align: center;
    border-radius: 4px;
  }

  .active {
    background-color: #3a8dff;
    color: #fff;
  }
}

.active {
  color: #409eff;
  background-color: #d9ecff;
}

.selectTag {
  margin-top: 10px;
}

.sc-input {
  flex: 1;
  margin-right: 40px;
  height: 32px;
  display: flex;
  flex-direction: row;
  align-items: start;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background-color: var(--el-fill-color-blank);

  .el-input-number {
    width: calc(100% / 7);
  }

  span {
    height: 32px;
    line-height: 34px;
  }
}

:deep(.sc-input-number) {
  &>.el-input>.el-input__wrapper {
    padding: 0px !important;
    border: none !important;
    box-shadow: none !important;

    &.is-focus {
      box-shadow: 0 0 0 1px var(--el-color-primary) !important;
    }
  }
}

.demo-ruleForm {
  :deep(.el-form-item__label) {
    justify-content: end;
  }
}

.cpi-content-toolbar {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-bottom: var(--main-padding) !important;

  .title {
    width: 80px;
  }
}

.entity-create-container {
  width: 100%;
  height: 100%;
  padding: var(--main-padding);
  display: flex;
  flex-direction: column;
}

.entity-create-wrapper {
  flex: 1;
  overflow-y: auto;
  @extend %scrollbar;
}

.entity-create-table {
  padding: var(--main-padding);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);

  :deep(.el-form-item) {
    margin-right: 40px;
  }
}

.entity-create-upload {
  height: 250px;
  padding: var(--main-padding);

  >div {
    float: left;
    display: flex;
    flex-direction: column;
    width: 400px;
    margin-bottom: var(--main-padding);

    .upload-model {
      .upload-demo {
        width: 300px;
      }
    }

    .upload-title {
      display: inline-block;
      margin-bottom: 20px;
    }
  }
}

.drawer-tag {
  .drawer-info-content {
    width: 100%;

    :deep(.el-input) {
      width: 250px;
    }
  }

  .drawer-configuration-header {
    margin-bottom: 20px;

    .info-text {
      color: #fff;
      position: relative;
      padding-left: 10px;

      &::before {
        content: "";
        position: absolute;
        left: 0;
        width: 4px;
        height: 100%;
        background-color: #3a8dff;
      }
    }
  }
}

.entity-create-submit {
  padding: 20px 0 7px 0;
  height: 60px;
  display: flex;
  background: #000b15;
  justify-content: center;
  align-items: center;
}

.equipment-name {
  width: 217px;
  text-align: center;
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  margin-top: 16px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  white-space: nowrap;
  /* 保证文本不换行 */
  overflow: hidden;
  /* 隐藏超出容器的内容 */
  text-overflow: ellipsis;
  /* 超出部分显示为省略号 */
}

.scenario-card {
  cursor: pointer;
  width: 30%;
  height: 250px;
}

.scenario-card-select {
  border: 1px solid #3a8dff;
}

.image-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f3f3f3;

  img {
    width: 100px;
    height: 100px;
  }

  /* background-color: #232b42; */
}

.scenario-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-plus {
  width: 217px;
  height: 166px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-info {
  position: absolute;
  width: 27px;
  height: 23px;
  top: 8px;
  right: 0px;
  cursor: pointer;
}
</style>
